#! /bin/sh
### BEGIN INIT INFO
# Provides:          brcm4330-patch
# Required-Start:    $local_fs
# Required-Stop:
# X-Start-Before:    bluetooth
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Patch firmware for brcm4330 Bluetooth adapter
# Description:       Patch firmware for brcm4330 Bluetooth adapter
### END INIT INFO

DEFAULTS="/etc/default/brcm4330"

# Include brcm4330 defaults if available
if [ -r "${DEFAULTS}" ]
then
	. "${DEFAULTS}"
fi

. /lib/lsb/init-functions

# exit if bluetooth utils are not installed
[ -f "/bin/hciconfig" ] || exit 0

do_start () {

if [ ! -z $(hciconfig | /bin/grep UART | /usr/bin/cut -d: -f1) ]
then
    log_action_begin_msg "brcm4330 device allready initialized"
    log_action_end_msg 0
    hcitool dev
else


    # Select MAC address
    if [ -z "$MAC_ADDR" ]; then
       log_warning_msg "No MAC_ADDR set in /etc/default/brcm4330, will use MAC 11:22:33:44:55:66"
       MAC_OPTIONS="--bd_addr 11:22:33:44:55:66"
    else
       MAC_OPTIONS="--bd_addr $MAC_ADDR"
    fi

    # Select tty port
    if [ -z "$PORT" ]; then
       log_warning_msg "No PORT set in /etc/default/brcm4330, will use ttymxc3"
       PORT="ttymxc3"
    fi

    # Start patching
    /bin/echo -en "" > /dev/$PORT      # pull down RTS on UART
    log_action_begin_msg  "Start pushing BRCM4330 bluetooth firmware to device and waiting 5 sec to complete"
    /usr/bin/timeout 20s /usr/local/bin/brcm_patchram_plus -d --patchram /lib/firmware/brcm/bcm4330.hcd  --baudrate 3000000 --use_baudrate_for_download /dev/$PORT --enable_hci --no2bytes --tosleep 1000 $MAC_OPTIONS  > /tmp/brcm4330.firmware > /dev/null 2>&1 &
    sleep 5
    case "$?" in
        0) log_action_end_msg 0
             # Enable interfaces
             hciconfig hci0 up
             #/usr/sbin/hciattach /dev/$PORT any
             ;;
        *) log_action_end_msg 1
             /bin/echo "Check /tmp/brcm4330.firmware for messages."
             ;;
    esac
fi
}

case "$1" in
  start)
	do_start
	;;
  restart|reload|force-reload)
	echo "Error: argument '$1' not supported" >&2
	exit 3
	;;
  stop)
	# No-op
	;;
  status)
	hcitool dev
	;;
  *)
	echo "Usage: brcm4330-patch.sh [start|stop|status]" >&2
	exit 3
	;;
esac

